package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.skyfishjy.library.RippleBackground;
import com.yuyh.library.view.image.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.IceCandidate;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.RendererCommon;
import org.webrtc.SessionDescription;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRendererGui;
import org.webrtc.VideoSource;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;

import static com.sam.im.heiqun.app.App.observer;
import static com.sam.im.heiqun.app.App.pc;

public class CalldideoActivity extends AppCompatActivity  {
    @BindView(R.id.img_friend_icon)
    CircleImageView imgFriendIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_invitation)
    TextView tvInvitation;
    @BindView(R.id.content_call)
    RippleBackground contentCall;
    @BindView(R.id.img_cancle2)
    ImageView imgCancle2;
    @BindView(R.id.img_as)
    ImageView imgAs;
    @BindView(R.id.layout_iscalling)
    RelativeLayout layoutIscalling;
    private CircleImageView img_icon;
    private TextView tvwiting;
    private ImageView bt_cancle;
    private TextView tv_cancle;
    private FragmentManager supportFragmentManager;
    private RippleBackground background;
    private int firsttag = -1;
    private static int START_LOCATION = 999;
    public static int CALL_VIDEO_CANCLE = 23311;
    public static int CALL_VIDEO_CANCLE_THE = 23310;
    private static Socket mSocket;
    private boolean istable; //是否切换了屏幕
    private ImageView bttable;
    private GLSurfaceView myVideoView;
    private VideoRenderer.Callbacks remoteRender;
    private VideoRenderer.Callbacks localRender;
    Timer timer = new Timer();
    private String userid;
    private String destid;
    private VideoSource videoSource;
    private int inwith = 100;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = new Message();
            message.what = START_LOCATION;
            myhandler.sendMessage(message);
        }
    };
    private boolean iscalling;//视屏中。。。。
    private MediaPlayer media;
    private Handler myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 999://对方长时间无响应
                    if (firsttag != -1) {
                        ToolsUtils.showToast(CalldideoActivity.this, getResources().getString(R.string.out_time_call));
                        timer.cancel();
                        background.stopRippleAnimation();
                        if (media != null && media.isPlaying()) {
                            media.stop();
                        }
                        setResult(CALL_VIDEO_CANCLE);
                        finish();
                    }
                    firsttag++;
                    break;
            }
        }
    };
    private String type;
    private String headurl;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        App.iscallvideoing = true;
        img_icon = (CircleImageView) findViewById(R.id.img_icon);
        tvwiting = (TextView) findViewById(R.id.tv_witing);
        bt_cancle = (ImageView) findViewById(R.id.bt_cancle);
        tv_cancle = (TextView) findViewById(R.id.tv_cancle);
        background = (RippleBackground) findViewById(R.id.content);
        bttable = (ImageView) findViewById(R.id.bt_table);
        headurl = getIntent().getStringExtra("headurl");
        type = getIntent().getStringExtra("type");
        userid = getIntent().getStringExtra("userid");
        destid = getIntent().getStringExtra("destid");
        name = getIntent().getStringExtra("name");
        if (headurl != null) {
            Glide.with(this).load(headurl).centerCrop().into(imgFriendIcon);
        }
        tvName.setText(name);
        timer.schedule(task, 10, 60000);
        int[] location = new int[2];
        int x = location[0];
        int y = location[1];
        Log.i("info", "destid==" + destid);
        // setfragments();
        if (type != null && type.equals("0")) {
            media = MediaPlayer.create(this, R.raw.phonering);
            media.setLooping(true);
            media.start();
            layoutIscalling.setVisibility(View.GONE);
            background.startRippleAnimation();
            Glide.with(this).load(headurl).centerCrop().into(img_icon);
        } else if (type != null && type.equals("1")) {
            tvwiting.setVisibility(View.GONE);
            tv_cancle.setVisibility(View.GONE);
            bt_cancle.setVisibility(View.GONE);
            bttable.setVisibility(View.VISIBLE);
            iscalling = true;
            timer.cancel();
        } else if (type != null && type.equals("21")) {
            tvwiting.setVisibility(View.GONE);
            tv_cancle.setVisibility(View.GONE);
            bt_cancle.setVisibility(View.GONE);
            bttable.setVisibility(View.VISIBLE);
            iscalling = true;
            timer.cancel();
        }
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                setResult(CALL_VIDEO_CANCLE);
                finish();
            }
        });
       /* myReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                ImMessage imMessage = (ImMessage) intent.getSerializableExtra("immessage");
                if (imMessage != null&&imMessage.getMessageType()==Constant.MESSAGE_TYPR_CALL_VIDEO_AS) {
                    Log.i("info","imessage=="+imMessage.toString());
                    switch (imMessage.getContent()){
                        case "0":
                            timer.cancel();
                            ToolsUtils.showToast(CalldideoActivity.this,"对方拒绝了您的视屏请求");
                            finish();
                            break;
                        case "1":
                            timer.cancel();
                            iscalling = true ;
                            ToolsUtils.showToast(CalldideoActivity.this,"对方接受了您的视屏请求");
                            if (media != null&&media.isPlaying()) {
                                media.stop();
                            }
                            bttable.setVisibility(View.VISIBLE);
                            img_icon.setVisibility(View.GONE);
                            tvwiting.setVisibility(View.GONE);
                            tv_cancle.setVisibility(View.GONE);
                            bt_cancle.setVisibility(View.GONE);
                            background.stopRippleAnimation();
                            background.setVisibility(View.GONE);
                            break;
                        case "2"://对方中断了当前视屏通话
                            ToolsUtils.showToast(CalldideoActivity.this,"对方中断了您们的视屏通话");
                            if (media != null&&media.isPlaying()) {
                                media.stop();
                            }
                            finish();
                            break;
                        case "3"://对方正在进行视屏通话
                            ToolsUtils.showToast(CalldideoActivity.this,"对方正在和他人视屏中，暂时无法接受邀请");
                            if (media != null&&media.isPlaying()) {
                                media.stop();
                            }
                            break;
                    }
                    background.stopRippleAnimation();
                }else if (imMessage != null&&imMessage.getMessageType()==Constant.MESSAGE_TYPR_CALL_VIDEO_AS){
                   if (imMessage.getContent().equals("0")){
                        //getmessage("3");//正在视屏 不能接受新的视屏
                   }
                }
            }
        };*/
       /* IntentFilter filter = new IntentFilter("easy.message");
        registerReceiver(myReceiver,filter);*/
       /* bttable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!istable){
                    FragmentTransaction fragmentTransaction2 = supportFragmentManager.beginTransaction();
                    fragmentTransaction2.commit();
                    FragmentTransaction fragmentTransaction1 = supportFragmentManager.beginTransaction();
                    fragmentTransaction1.commit();
                    istable =  true;
                }else {
                    FragmentTransaction fragmentTransaction2 = supportFragmentManager.beginTransaction();
                    fragmentTransaction2.commit();
                    FragmentTransaction fragmentTransaction1 = supportFragmentManager.beginTransaction();
                    fragmentTransaction1.commit();
                    istable =  false;
                }
            }
        });*/
        try {
            initWebrtc();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void getCallMessage(ImMessage msg) {
        Log.i("info", "这里接收到的消息===" + msg.toString());
        switch (msg.getMessageType()) {
            case Constant.MESSAGE_TYPR_CALL_ICE:
//                ToolsUtils.showToast(this,"收到消息49");
                JSONObject contentjs= null;
                try {
                    contentjs = new JSONObject(msg.getContent());
                    IceCandidate candidate = new IceCandidate(
                            contentjs.getString("sdpMid"),
                            contentjs.getInt("sdpMLineIndex"),
                            contentjs.getString("candidate")
                    );
                    App.pc.addIceCandidate(candidate);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case Constant.MESSAGE_TYPR_CALL_ANSWER:
                timer.cancel();
                iscalling = true;
                ToolsUtils.showToast(CalldideoActivity.this, getResources().getString(R.string.other_jie_call));
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                bttable.setVisibility(View.VISIBLE);
                img_icon.setVisibility(View.GONE);
                tvwiting.setVisibility(View.GONE);
                tv_cancle.setVisibility(View.GONE);
                bt_cancle.setVisibility(View.GONE);
                background.stopRippleAnimation();
                background.setVisibility(View.GONE);
                JSONObject content1 = null;
                try {
                    content1 = new JSONObject(msg.getContent());
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(content1.getString("type")),
                            content1.getString("sdp"));
                    pc.setRemoteDescription(observer, sdp);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    public void initWebrtc() throws Exception {
        if (PeerConnectionFactory.initializeAndroidGlobals(
                this.getApplicationContext(),
                true,
                true,
                true)) {
            Toast.makeText(this, getResources().getString(R.string.init_success), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, getResources().getString(R.string.init_fail), Toast.LENGTH_SHORT).show();
        }
        //获取配置

        myVideoView = (GLSurfaceView) findViewById(R.id.myVideo);
        myVideoView.setPreserveEGLContextOnPause(true);
        myVideoView.setKeepScreenOn(true);
        VideoRendererGui.setView(myVideoView, new Runnable() {
            @Override
            public void run() {

            }
        });


        GLSurfaceView friendVideoView = (GLSurfaceView) findViewById(R.id.friendVideo);
        VideoRendererGui.setView(friendVideoView, new Runnable() {
            @Override
            public void run() {

            }
        });
        remoteRender = VideoRendererGui.createGuiRenderer(0, 0,
                inwith, inwith, RendererCommon.ScalingType.SCALE_ASPECT_FILL, true);

        /*if (type != null && type.equals("21")) {
            JSONObject contentjs = null;
            try {
                ImMessage immessage = (ImMessage) getIntent().getSerializableExtra("immessage");
                contentjs = new JSONObject(immessage.getContent());
                SessionDescription sdp = new SessionDescription(
                        SessionDescription.Type.fromCanonicalForm(contentjs.getString("type")),
                        contentjs.getString("sdp"));
                pc.setRemoteDescription(observer, sdp);
                //发送answer消息
                JSONObject payload = new JSONObject();
                payload.put("type", sdp.type.canonicalForm());
                payload.put("sdp", sdp.description);
                String sendSdp = payload.toString();
                getmessage(sendSdp, Constant.MESSAGE_TYPR_CALL_ANSWER, 213);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }*/
        if (type!=null&&type.equals("1")) {
            if (media != null && media.isPlaying()) {
                media.stop();
            }
            tvwiting.setVisibility(View.GONE);
            tv_cancle.setVisibility(View.GONE);
            bt_cancle.setVisibility(View.GONE);
            bttable.setVisibility(View.VISIBLE);
            iscalling = true;
            timer.cancel();
            layoutIscalling.setVisibility(View.GONE);

            JSONObject contentjs = null;
            try {
                ImMessage immessage = (ImMessage) getIntent().getSerializableExtra("immessage");
                contentjs = new JSONObject(immessage.getContent());
                SessionDescription sdp = new SessionDescription(
                        SessionDescription.Type.fromCanonicalForm(contentjs.getString("type")),
                        contentjs.getString("sdp"));
                pc.setRemoteDescription(observer, sdp);
                //发送answer消息
                JSONObject payload = new JSONObject();
                payload.put("type", sdp.type.canonicalForm());
                payload.put("sdp", sdp.description);
                String sendSdp = payload.toString();
                getmessage(sendSdp, Constant.MESSAGE_TYPR_CALL_ANSWER, 213);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void getmessage(String content, int type, int msgtype) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        String fromid = ToolsUtils.getMyUserId();
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, msgtype, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, Long.parseLong(destid), content, type,
                currentTime, System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, ToolsUtils.getUser().getHeadUrl());
        if (content.equals("3")) {
            imMessage.save();
        }
        //EventBus.getDefault().post(imMessage);
        socketSend(imMessage);
    }

    private void setplayerfragment() {
        FragmentTransaction fragmentTransaction2 = supportFragmentManager.beginTransaction();
        //  playerfragment = new PlayFragment();
        //fragmentTransaction2.replace(R.id.player,playerfragment);
        fragmentTransaction2.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (iscalling) {
                showdialog();
            } else {
                setResult(CALL_VIDEO_CANCLE);
                finish();
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.tip_exit));
        builder.setMessage(getResources().getString(R.string.you_exit_call));
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // getmessage("2");

                ToolsUtils.showToast(CalldideoActivity.this, "视屏通话已断开");
                finish();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();//这里要在初始完之后进行设置
        alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.blue));
        alertDialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
    }

    @Override
    protected void onPause() {
        super.onPause();
        myVideoView.onPause();
        App.pc.close();
        App.pc.dispose();
        if (videoSource != null) {
            videoSource.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        myVideoView.onResume();

    }

    @Override
    protected void onStop() {
        finish();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (media != null && media.isPlaying()) {
            media.stop();
        }
        timer.cancel();
        App.iscallvideoing = false;
        App.pc.dispose();
        if (videoSource != null) {
            videoSource.dispose();
        }
        EventBus.getDefault().unregister(this);
        App.pcFactory.dispose();
        myhandler.removeCallbacks(null);
    }

    private void setfragments() {
        supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction1 = supportFragmentManager.beginTransaction();
        //fragmentTransaction1.replace(R.id.pusher,streamFragment);
        fragmentTransaction1.commit();
        // setplayerfragment();
    }

   /* public void onSettings(View view) {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }*/

    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub) {
        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;

            @Override
            public void run() {
                tbub.save();
                ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                socketSend(imMessage);
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 10) {
                    mSocket = App.socket;
                    retryCount++;
                    if (mSocket != null) {
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                                    imMessage.delete();
                                }
                                //sendMessageHandler.sendEmptyMessage(SEND_OK);
                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null || !mSocket.connected()) {//mSocket 为空  这个基本不会出现 、或者链接断开了
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
        }
    }



    @OnClick({R.id.img_cancle2, R.id.img_as})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_cancle2:

                break;
            case R.id.img_as:
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                tvwiting.setVisibility(View.GONE);
                tv_cancle.setVisibility(View.GONE);
                bt_cancle.setVisibility(View.GONE);
                bttable.setVisibility(View.VISIBLE);
                iscalling = true;
                timer.cancel();
                layoutIscalling.setVisibility(View.GONE);

                JSONObject contentjs = null;
                try {
                    ImMessage immessage = (ImMessage) getIntent().getSerializableExtra("immessage");
                    contentjs = new JSONObject(immessage.getContent());
                    SessionDescription sdp = new SessionDescription(
                            SessionDescription.Type.fromCanonicalForm(contentjs.getString("type")),
                            contentjs.getString("sdp"));
                    pc.setRemoteDescription(observer, sdp);
                    //发送answer消息
                    JSONObject payload = new JSONObject();
                    payload.put("type", sdp.type.canonicalForm());
                    payload.put("sdp", sdp.description);
                    String sendSdp = payload.toString();
                    getmessage(sendSdp, Constant.MESSAGE_TYPR_CALL_ANSWER, 213);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}

